package android.handler;

import java.util.concurrent.*;

/**
 * @author Ajie
 * @date 2021-03-15
 * @function
 */
public class Handler {
    private Looper looper;
    private MessageQueue messageQueue;


    public Handler() {
        looper = Looper.myLooper();
        messageQueue = looper.mQueue;
    }

    public void handlerMessage(Message msg) {

    }

    public void sendMessage(Message msg) {
        // 将消息放入消息队列MessageQueue中
        enqueueMessage(msg);
    }

    public void sendEmptyMessage(int what) {
        Message message = new Message();
        message.target = Handler.this;
        message.what = what;
        message.obj = null;
        sendMessage(message);
    }

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);//为了 dealy 发送
    private final ConcurrentHashMap<Integer, ScheduledFuture<?>> delayedMessages = new ConcurrentHashMap<>();//为了 remove  dealy msg
    public void sendEmptyMessageDelayed(int what, long delayMillis) {
        ScheduledFuture<?> scheduledFuture = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.target = Handler.this;
                message.what = what;
                message.obj = null;
                sendMessage(message);
                delayedMessages.remove(what);
            }
        }, delayMillis, TimeUnit.MILLISECONDS);
        delayedMessages.put(what, scheduledFuture);
    }



    private void enqueueMessage(Message msg){
        // 赋值当前消息处理对象
        msg.target = this;
        // 使用MessageQueue，将消息传入
        messageQueue.enqueueMessage(msg);
    }

    public void dispatchMessage(Message msg){
        handlerMessage(msg);
    }

    public final void removeMessages(int what) {
        ScheduledFuture<?> scheduledFuture = delayedMessages.get(what);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(false);
            delayedMessages.remove(what);
        }

        messageQueue.removeMessages(this, what);
    }}
